﻿using System;
using System.Data;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using _18miljard.Db;
using _18miljard.Config;

namespace _18miljard.Mail
{
	public class BulkEMail : Collection<EMail>
	{
		internal void Send(bool personalized)
		{
			if (this.Count == 0)
				return;

			this.Queue(personalized);

			Global.MailSignal();
		}

		internal void Add(BulkEMail emails)
		{
			foreach (EMail email in emails)
				this.Add(email);
		}

		internal void Queue(bool personalized)
		{
			/*
			 * personalized = true: assumes that every email has a unique body which causes the mailTextId to be updated for each mail.
			 * personalized = false: assumes the first mail in the collection has the body for the rest of the mails in the collection.
			 */

			if (this.Count == 0)
				return;

			int beginTextId = EMail.GetNextTextId();

			QueryCollection queries = new QueryCollection(WebConfig.MailConnectionParameters);

			for (int i=0; i<this.Count; i++)
			{
				EMail email = this[i];

				if (personalized || i == 0)
					queries.Add(email.QueueBatchSingle(beginTextId));
				else
					queries.Add(email.QueueBatch(beginTextId));
				
				if (personalized)
					beginTextId++;
			}

			queries.Execute();
		}
	}
}
